//
//  ProductDetailViewController.m
//  华康通
//
//  Created by leiyu on 16/4/8.
//  Copyright © 2016年 华康集团. All rights reserved.
//

#import "ProductDetailViewController.h"
#import "PayViewController.h"
#import "SignViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

@interface ProductDetailViewController ()<UIWebViewDelegate,UIScrollViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate, NJKWebViewProgressDelegate,LGPhotoPickerViewControllerDelegate>

@property (strong, nonatomic) IBOutlet UIWebView *myWebView;
//创建一个对象
@property (strong, nonatomic) TRJSExport* jsExport;
@property (strong, nonatomic) ShareView* shareView;
@property (strong, nonatomic) TRJSExport* test;
//保存要传给html5的数据
//@property (strong, nonatomic) NSString* imageStr;


//返回按钮
@property (nonatomic, strong) UIBarButtonItem *backItem;
//关闭按钮
@property (nonatomic, strong) UIBarButtonItem *closeItem;
//保存图片类型的参数
@property (nonatomic, strong) NSString* imageType;

@property (strong, nonatomic) NJKWebViewProgressView* webViewProgressView;
@property (strong, nonatomic) NJKWebViewProgress* webViewProgress;

@property (nonatomic, assign) LGShowImageType showType;

//标记是个人签名页面的值；
@property (nonatomic, unsafe_unretained) NSInteger shareIndex;


@property (nonatomic, strong) NSString* backClosedIndex;
@property (nonatomic, strong) NSString* closedBtnIndex;

@end

@implementation ProductDetailViewController

//[[UIApplication sharedApplication].keyWindow addSubview:self.myIconButton];

- (UIBarButtonItem *)closeItem
{
    if (!_closeItem)
    {
        _closeItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeNative)];
    }
    return _closeItem;
}


- (UIBarButtonItem *)backItem
{
    if (!_backItem) {
        _backItem = [[UIBarButtonItem alloc] init];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        UIImage *image = LoadImage(@"back1");
        [btn setImage:image forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(backNative) forControlEvents:UIControlEventTouchUpInside];
        //字体的多少为btn的大小
        [btn sizeToFit];
        //左对齐
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        //让返回按钮内容继续向左边偏移15，如果不设置的话，就会发现返回按钮离屏幕的左边的距离有点儿大，不美观
        btn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        btn.frame = CGRectMake(0, 0, 40, 40);
        _backItem.customView = btn;
    }
    return _backItem;
}

- (ShareView*)shareView
{
    if (!_shareView)
    {
        _shareView = [[ShareView alloc]initWithFrame:CGRectMake(0, UISCREENHEIGHT - 125, UISCREENWEITH, 125) withIndex:self.shareIndex];
    }
    return _shareView;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    
    [MobClick beginLogPageView:@"ProductDetailViewController"];//("PageOne"为页面名称，可自定义)
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.webViewProgressView removeSubviews];
//    [self.navigationController.navigationBar setBarTintColor:KMainColor];
//    [self.navigationController.navigationBar setTintColor:FFFFFFColor];
//    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:SetFont(20.0),NSForegroundColorAttributeName:FFFFFFColor}];
//
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
//    [self setNeedsStatusBarAppearanceUpdate];

    [MobClick endLogPageView:@"ProductDetailViewController"];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.shareIndex = 1;
    UIScrollView *tempView = (UIScrollView *)[self.myWebView.subviews objectAtIndex:0];
    tempView.showsVerticalScrollIndicator = NO;
    tempView.showsHorizontalScrollIndicator = NO;
    tempView.delegate = self;
    //设置不弹性
    tempView.bounces = NO;

    self.navigationItem.leftBarButtonItems = @[self.backItem, self.closeItem];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(share)];
    [self showProgressView];
}


//加载链接
- (void)loadURl
{
//    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://dev.wap.kangbaotong.cn/static/test.html"]];
//    [self.myWebView loadRequest:request];
    
    if (![self.gotoUrl isEqualToString:@""] && self.gotoUrl)
    {
        if (self.target)
        {
            if ([self.target isEqualToString:@"native"])
            {
                [self setFrameForWebView];
                NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.gotoUrl]];
                [self.myWebView loadRequest:request];
            }
            else if ([self.target isEqualToString:@"external"])
            {
                //utf8转码
                NSString* urlString = [self.gotoUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
                NSLog(@".............外链网址字符串%@\n",self.gotoUrl);
                NSLog(@".............外链网址%@",[NSURL URLWithString:[NSString stringWithFormat:@"%@",urlString]]);
                [self setFrameForWebView];
                NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.gotoUrl]];
                [self.myWebView loadRequest:request];
            }
        }
        else
        {
            //utf8转码
            NSString* urlString = [self.gotoUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            NSLog(@".............外链网址字符串%@\n",self.gotoUrl);
            NSLog(@".............外链网址%@",[NSURL URLWithString:[NSString stringWithFormat:@"%@",urlString]]);
            [self setFrameForWebView];
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.gotoUrl]];
            [self.myWebView loadRequest:request];
        }
    }
    else
    {
        [self setFrameForWebView];
        NSLog(@".............网址%@",[NSURL URLWithString:[NSString stringWithFormat:@"%@?productId=%@&agentId=%@&rand=%@&cost=%@&isbuy=%@&app=1&isHideNavi=1",TEXT_URL,self.productId,[TRUserAgenCode getCustomerId],[self getRand],[self isOn],self.isSell]]);
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?productId=%@&agentId=%@&rand=%@&cost=%@&isbuy=%@&app=1&isHideNavi=1",TEXT_URL,self.productId,[TRUserAgenCode getCustomerId],[self getRand],[self isOn],self.isSell]]];
        //          NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://118.178.86.38/h5/static/hengda/underwriting.html"]];
        self.selfURL = [NSString stringWithFormat:@"%@?productId=%@&agentId=%@&rand=%@&cost=%@&isbuy=%@&app=1&isHideNavi=1",TEXT_URL,self.productId,[TRUserAgenCode getCustomerId],[self getRand],[self isOn],self.isSell];
        [self.myWebView loadRequest:request];
    }
}
//不同页面跳转过来web视图的高度
- (void)setFrameForWebView
{
    if (self.isFirst)
    {
        self.myWebView.frame = CGRectMake(0, 0, UISCREENWEITH, UISCREENHEIGHT - NavigationBarHeight - StatusBarHeight);
    }
    else
    {
        self.myWebView.frame = CGRectMake(0, 0, UISCREENWEITH, UISCREENHEIGHT - StatusBarHeight - NavigationBarHeight);
    }
}
//创建进度条
- (void)showProgressView
{
    self.webViewProgress = [[NJKWebViewProgress alloc] init];
    self.myWebView.delegate = self.webViewProgress;
    self.webViewProgress.webViewProxyDelegate = self;
    self.webViewProgress.progressDelegate = self;
    
    CGRect navBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0,
                                 navBounds.size.height - 3,
                                 navBounds.size.width,
                                 3);
    self.webViewProgressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    self.webViewProgressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [self.webViewProgressView setProgress:0 animated:YES];
    [self loadURl];
    [self.navigationController.navigationBar addSubview:self.webViewProgressView];
}

- (void)isSuccessForSingle
{
    //出单成功页面隐藏去掉导航栏上面的按钮,其他页面不隐藏——————————————
    if ([self.title isEqualToString:@"出单成功"])
    {
        self.navigationItem.leftBarButtonItems = nil;
        self.navigationItem.hidesBackButton = YES;
        self.navigationItem.rightBarButtonItem = nil;
    }
    else
    {
        self.navigationItem.leftBarButtonItems = @[self.backItem, self.closeItem];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(share)];
    }
}

#pragma mark - NJKWebViewProgressDelegate
- (void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [self.webViewProgressView setProgress:progress animated:YES];
    self.title = [self.myWebView stringByEvaluatingJavaScriptFromString:@"document.title"];
}

//判断并且登录
- (void)judeLoginWithMessage:(NSString*)message
{
    ShowLogin(self.navigationController);
}

//外链分享
- (void)share
{
    if (![self.gotoUrl isEqualToString:@""] && self.gotoUrl)
    {
        if (self.target)
        {
            if ([self.target isEqualToString:@"native"])
            {
                [self addShareWithH5];
            }
            else if ([self.target isEqualToString:@"external"])
            {
                [self addShareWithSelf];
            }
            else
            {
                [self addShareWithH5];
            }
        }
        else
        {
            [self addShareWithSelf];
        }
    }
    else
    {
        [self addShareWithH5];
    }
}

//自己设置分享方法
- (void)addShareWithSelf
{
    if ([TRUserAgenCode isLogin])
    {
        if (self.small_picture && self.product_features && self.title && (self.gotoUrl || self.selfURL))
        {
            self.shareView.message = [NSString stringWithFormat:@"%@!#%@!#%@!#%@",self.title,self.small_picture,self.product_features,self.gotoUrl];
            if (self.selfURL && ![self.selfURL isEqualToString:@""])
            {
                self.shareView.message = [NSString stringWithFormat:@"%@!#%@!#%@!#%@",self.title,self.small_picture,self.product_features,self.selfURL];
            }
        }
        else
        {
            self.shareView.message = [NSString stringWithFormat:@"未知信息!#分享内容不存在!#1!#http://wap.kangbaotong.cn"];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication].keyWindow addSubview:self.shareView.backView];
            [[UIApplication sharedApplication].keyWindow addSubview:self.shareView];
        });
    }
    else
    {
        [self judeLoginWithMessage:@"您还没登录，请先登录!"];
    }
}

//调用h5页面的分享方法
- (void)addShareWithH5
{
    NSString* message = [self.myWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"appShare()"]];
    NSLog(@"分享message = %@",message);
    self.shareView.message = message;
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication].keyWindow addSubview:self.shareView.backView];
        [[UIApplication sharedApplication].keyWindow addSubview:self.shareView];
    });
}

- (void)backNative
{
    //获取h5链接
    NSString *currentURL = [self.myWebView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
    NSLog(@"self.target = %@ currentURL = %@",self.target,currentURL);
    /* url截取字符‘?’为数组 */
    NSArray  *array = [currentURL componentsSeparatedByString:@"?"];
    /* 拿到第一个元素，并判断第一个元素的url */
    if (array && array.count > 0)
    {
        NSString * mainURL = array[0];
        [self backMainPageWithURL:mainURL];
    }
    else
    {
        [self backMainPageWithURL:currentURL];
    }
}

/* h5页面的判断返回 */
- (void)backMainPageWithURL:(NSString*)url
{
    if ([url rangeOfString:WLHTTP].location != NSNotFound)
    {
        if (![self.gotoUrl isEqualToString:@""] && self.gotoUrl)
        {
            if (self.target)
            {
                if ([self.target isEqualToString:@"native"])
                {
                    [self addBackWithH5];
                }
                else if ([self.target isEqualToString:@"external"])
                {
                    [self addBackWithSelf];
                }
                else
                {
                    [self addBackWithH5];
                }
            }
            else
            {
                [self addBackWithSelf];
            }
        }
        else
        {
            [self addBackWithH5];
        }
    }
    else
    {
        [self addBackWithSelf];
    }
}

//自己设置返回
- (void)addBackWithSelf
{
    //判断是否有上一层H5页面
    if ([self.myWebView canGoBack])
    {
        //如果有则返回
        [self.myWebView goBack];
        //同时设置返回按钮和关闭按钮为导航栏左边的按钮
        self.navigationItem.leftBarButtonItems = @[self.backItem, self.closeItem];
    }
    else
    {
        [self closeNative];
    }
}

//调用h5返回上一页面的方法
- (void)addBackWithH5
{
    [self.myWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"appBack()"]];
}

//关闭H5页面，直接回到原生页面
- (void)closeNative
{
    [self.navigationController popViewControllerAnimated:YES];
}

//显示推广费用的开关
- (NSString*)isOn
{
    if ([TRUserAgenCode isLogin])
    {
        NSNumber* number = [CacheData getCache:@"ISSHOWTGF"];
        if (number != nil)
        {
            if ([number boolValue])
            {
                return @"1";
            }
            else
            {
                return @"0";
            }
        }
        else
        {
            return @"1";
        }
    }
    else
    {
        return @"0";
    }
}

//产生一个随机数
- (NSString*)getRand
{
    NSInteger rand = arc4random()%2000000000000;
    return [NSString stringWithFormat:@"%ld",(long)rand];
}

#pragma  mark - web视图完成调用后执行（代理方法）

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.test = [[TRJSExport alloc]init];
    [self.test returnTitleForJS:^(NSString *title) {
        NSLog(@"h5返回来的界面标题 = %@",title);
        self.title = title;
    }];
    
    
    
    [self.test returnBoolForJS:^(NSInteger isBack) {
        [self cleanCacheAndCookie];
        //            [self dismissViewControllerAnimated:YES completion:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [self.test postMessageForJS:^{
        NSLog(@"h5调用原生方法是否安装微信");
    }];
    
    //是否隐藏‘分享’按钮
    [self.test returnhideShareButtonForJS:^(NSString *message) {
        NSLog(@"h5返回来的是否隐藏导航了分享按钮的值");
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([message isEqualToString:@"1"])
            {
                self.navigationItem.rightBarButtonItem = nil;
            }
            else
            {
                self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(share)];
            }
        });
    }];
    
    [self.test returnBackBtnClosed:^(NSString *message) {
        self.backClosedIndex = message;
        NSLog(@"h5返回来的是否关闭“关闭'按钮的值：%@",self.backClosedIndex);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hidenButton];
        });
    }];
    
    [self.test returnCloseBtnClosed:^(NSString *message) {
        self.closedBtnIndex = message;
        NSLog(@"h5返回来的是否关闭“关闭'按钮的值：%@",self.closedBtnIndex);
    }];
    
    [self.test returnJudgSignPageForJS:^(NSString *message) {
        NSLog(@"分享message = %@",message);
        ShareView* shareView = [[ShareView alloc]initWithFrame:CGRectMake(0, UISCREENHEIGHT - 125, UISCREENWEITH, 125) withIndex:0];
        shareView.message = message;
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication].keyWindow addSubview:shareView.backView];
            [[UIApplication sharedApplication].keyWindow addSubview:shareView];
        });
    }];
    
    [self.test returnMessageForJS:^(NSString *message) {
        NSLog(@"分享message = %@",message);
        ShareView* shareView = [[ShareView alloc]initWithFrame:CGRectMake(0, UISCREENHEIGHT - 125, UISCREENWEITH, 125) withIndex:0];
        shareView.message = message;
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication].keyWindow addSubview:shareView.backView];
            [[UIApplication sharedApplication].keyWindow addSubview:shareView];
        });
    }];
    [self.test returnPayForJS:^(NSString *content) {
        dispatch_async(dispatch_get_main_queue(), ^{
            PayViewController* payVC = [[PayViewController alloc]initWithNibName:@"PayViewController" bundle:nil];
            payVC.content = content;
            [self.navigationController pushViewController:payVC animated:YES];
        });
    }];
    [self.test returnPhotoForJS:^(NSString* index) {
        self.imageType = index;
        NSLog(@"图片类型 = %@",self.imageType);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self photo];
        });
    }];
    [self.test returnDrawForJS:^(NSString *index) {
        self.imageType = index;
        NSLog(@"签名图片类型 = %@",self.imageType);
        NSString* str = @"0";
        if ([index rangeOfString:@"-"].location != NSNotFound)
        {
            NSArray* a = [index componentsSeparatedByString:@"-"];
            if (a.count > 2)
            {
                str = a[2];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self drawSignatureWithType:str];
        });
    }];
    context[@"testobject"] = self.test;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //首先创建JSContext 对象（此处通过当前webView的键获取到jscontext）
    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.test = [[TRJSExport alloc]init];
    [self.test returnTitleForJS:^(NSString *title) {
        NSLog(@"h5返回来的界面标题 = %@",title);
        self.title = title;
    }];
    [self.test returnBoolForJS:^(NSInteger isBack) {
        [self cleanCacheAndCookie];
        //            [self dismissViewControllerAnimated:YES completion:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    //是否隐藏‘分享’按钮
    [self.test returnhideShareButtonForJS:^(NSString *message) {
        NSLog(@"h5返回来的是否隐藏导航了分享按钮的值");
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([message isEqualToString:@"1"])
            {
                self.navigationItem.rightBarButtonItem = nil;
            }
            else
            {
                self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(share)];
            }
        });
    }];
    
    [self.test returnBackBtnClosed:^(NSString *message) {
        self.backClosedIndex = message;
        NSLog(@"h5返回来的是否关闭“关闭'按钮的值：%@",self.backClosedIndex);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hidenButton];
        });
    }];
    
    [self.test postMessageForJS:^{
        NSLog(@"h5调用原生方法是否安装微信");
    }];
    
    [self.test returnCloseBtnClosed:^(NSString *message) {
        self.closedBtnIndex = message;
        NSLog(@"h5返回来的是否关闭“关闭'按钮的值：%@",self.closedBtnIndex);
    }];
    
    
    [self.test returnJudgSignPageForJS:^(NSString *message) {
        NSLog(@"分享message = %@",message);
        ShareView* shareView = [[ShareView alloc]initWithFrame:CGRectMake(0, UISCREENHEIGHT - 125, UISCREENWEITH, 125) withIndex:0];
        shareView.message = message;
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication].keyWindow addSubview:shareView.backView];
            [[UIApplication sharedApplication].keyWindow addSubview:shareView];
        });
    }];
    
    [self.test returnMessageForJS:^(NSString *message) {
        NSLog(@"分享message = %@",message);
        ShareView* shareView = [[ShareView alloc]initWithFrame:CGRectMake(0, UISCREENHEIGHT - 125, UISCREENWEITH, 125) withIndex:0];
        shareView.message = message;
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication].keyWindow addSubview:shareView.backView];
            [[UIApplication sharedApplication].keyWindow addSubview:shareView];
        });
    }];
    [self.test returnPayForJS:^(NSString *content) {
        dispatch_async(dispatch_get_main_queue(), ^{
            PayViewController* payVC = [[PayViewController alloc]initWithNibName:@"PayViewController" bundle:nil];
            payVC.content = content;
            [self.navigationController pushViewController:payVC animated:YES];
        });
    }];
    [self.test returnPhotoForJS:^(NSString* index) {
        self.imageType = index;
        NSLog(@"图片类型 = %@",self.imageType);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self photo];
        });
    }];
    
    [self.test returnDrawForJS:^(NSString *index) {
        self.imageType = index;
        NSLog(@"签名图片类型 = %@",self.imageType);
        NSString* str = @"0";
        if ([index rangeOfString:@"-"].location != NSNotFound)
        {
            NSArray* a = [index componentsSeparatedByString:@"-"];
            if (a.count > 2)
            {
                str = a[2];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self drawSignatureWithType:str];
        });
    }];
    context[@"testobject"] = self.test;
    
}

- (void)hidenButton
{
    if (self.backClosedIndex.length == 2)
    {
        NSString * str1 = [self.backClosedIndex substringToIndex:1];
        NSString * str2 = [self.backClosedIndex substringFromIndex:1];
        NSLog(@"str1 = %@, str2 = %@",str1,str2);
        if ([str1 isEqualToString:@"1"] && [str2 isEqualToString:@"1"])
        {
            //隐藏返回按钮
            [self.navigationItem setHidesBackButton:YES];
            self.navigationItem.leftBarButtonItems = @[];
        }
        else if ([str1 isEqualToString:@"1"] && ![str2 isEqualToString:@"1"])
        {
            self.navigationItem.leftBarButtonItems = @[self.closeItem];
        }
        else if (![str1 isEqualToString:@"1"] && [str2 isEqualToString:@"1"])
        {
            self.navigationItem.leftBarButtonItems = @[self.backItem];
        }
        else
        {
            self.navigationItem.leftBarButtonItems = @[self.backItem,self.closeItem];
        }
    }
}

//画一个电子签名
- (void)drawSignatureWithType:(NSString*)type
{
    SignViewController *signVC = [[SignViewController alloc] init];
    signVC.type = type;
//    signVC.signLineColorDic = @{@"red":@(0.0),@"green":@(0.0),@"blue":@(0.0),@"alpha":@1.0};
//    [self presentViewController:signVC animated:YES completion:nil];
    [self.navigationController pushViewController:signVC animated:YES];
    [signVC signResultWithBlock:^(UIImage *signImage) {
        //下面是上传照片到后台（图片上传功能）
        [self postImageWithImage:signImage withType:@"1"];
    }];
}

/**
 *  初始化相册选择器
 */
- (void)presentPhotoPickerViewControllerWithStyle:(LGShowImageType)style
{
    LGPhotoPickerViewController *pickerVc = [[LGPhotoPickerViewController alloc] initWithShowType:style];
    pickerVc.status = PickerViewShowStatusCameraRoll;
    pickerVc.maxCount = 1;   // 最多能选1张图片
    pickerVc.delegate = self;
    self.showType = style;
    [pickerVc showPickerVc:self];
}

/**
 *  初始化自定义相机（单拍）
 */
- (void)presentCameraSingle
{
    ZLCameraViewController *cameraVC = [[ZLCameraViewController alloc] init];
    // 拍照最多个数
    cameraVC.maxCount = 1;
    // 单拍
    cameraVC.cameraType = ZLCameraSingle;
    cameraVC.callback = ^(NSArray *cameras){
        //在这里得到拍照结果
        //数组元素是ZLCamera对象
        ZLCamera *canamerPhoto = [cameras lastObject];
        UIImage *image = canamerPhoto.photoImage;
        //下面是上传照片到后台（图片上传功能）
        [self postImageWithImage:image withType:@"0"];
    };
    [cameraVC showPickerVc:self];
}

#pragma mark - LGPhotoPickerViewControllerDelegate

- (void)pickerViewControllerDoneAsstes:(NSArray *)assets isOriginal:(BOOL)original
{
    //assets的元素是LGPhotoAssets对象，获取image方法如下:
    NSMutableArray *originImage = [NSMutableArray array];
    for (LGPhotoAssets *photo in assets)
    {
        //原图
        [originImage addObject:photo.originImage];
    }
    [self postImageWithImage:[[originImage copy] lastObject] withType:@"0"];
}

//拍照
- (void)photo
{
    [SRActionSheet sr_showActionSheetViewWithTitle:@"请选择上传方式"
                                 cancelButtonTitle:@"取消"
                            destructiveButtonTitle:nil
                                 otherButtonTitles:@[@"拍照", @"相册"]
                                  selectSheetBlock:^(SRActionSheet *actionSheetView, NSInteger actionIndex) {
                                      switch (actionIndex)
                                      {
                                          case -1:
                                              return;
                                              break;
                                          case 1:
                                          {
                                              [self presentPhotoPickerViewControllerWithStyle:LGShowImageTypeImagePicker];
                                          }
                                              break;
                                          case 0:
                                          {
                                              [self presentCameraSingle];
                                          }
                                              break;
                                          default:
                                              break;
                                      }
                                  }];
}

//OC调用js里面的方法（传证件照片服务端返回来的数据）
- (void)postMessageToJSWithStr:(NSString*)imageStr
{
    //第二种调用js方法
    [self.myWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"getpicdata('%@')",imageStr]];
}

//OC调用js里面的方法（传电子签名服务端返回来的数据）
- (void)postSignatureToJSWithStr:(NSString*)imageStr
{
    [self.myWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"getidsign('%@')",imageStr]];
}

//判断一个字符串里面是否包含 0-9 的数字
- (BOOL)isContainNumberWithString:(NSString*)str
{
    NSMutableArray* array = [NSMutableArray array];
    NSArray* arr = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"];
    for (NSString* s in arr)
    {
        if ([str rangeOfString:s].location != NSNotFound)
        {
            [array addObject:s];
        }
    }
    if (array.count == 0)
    {
        NSLog(@"字符串里面没有包含数字！");
        return NO;
    }
    else
    {
        NSLog(@"字符串里面包含数字！");
        return YES;
    }
}

//下面是上传照片到后台（图片上传功能）
- (void)postImageWithImage:(UIImage*)image withType:(NSString*)type
{
    PostImageView* postIV = [[PostImageView alloc]init];
    postIV.companyCode = @"ax";
    postIV.fileSuffix = @"jpg";
    postIV.pictureType = @"999";
    if (self.imageType)
    {
        if ([self isContainNumberWithString:self.imageType])
        {
            if ([self.imageType rangeOfString:@"-"].location != NSNotFound)
            {
                NSArray* a = [self.imageType componentsSeparatedByString:@"-"];
                postIV.pictureType = a[1];
                postIV.fileSuffix = a[0];
                if ([type isEqualToString:@"0"])
                {
                    if (a.count > 2)
                    {
                        postIV.companyCode = [a lastObject];
                    }
                }
                else
                {
                    if (a.count > 3)
                    {
                        postIV.companyCode = [a lastObject];
                    }
                }
            }
            else
            {
                postIV.pictureType = self.imageType;
            }
        }
    }
    NSLog(@"postIV.pictureType = %@,postIV.fileSuffix = %@",postIV.pictureType,postIV.fileSuffix);
    postIV.customerId = [TRUserAgenCode getCustomerId];
    postIV.transType = @"APP";
    XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
    [postIV saveWithImage:image withImageName:@"certificates" withURL:POSTIMAGE_URL withType:type success:^(NSData *data) {
        id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        if ([result isKindOfClass:[NSDictionary class]])
        {
            NSString* str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"json流转化为字符串：%@",str);
            //把json转成字符串
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([type isEqualToString:@"0"])
                {
                    [statusBar showStatusMessage:@"上传照片成功..."];
                    //上传照片后把json返回给h5
                    [self postMessageToJSWithStr:str];
                    
                }
                else
                {
                    [statusBar showStatusMessage:@"上传电子签名成功..."];
                    //上传签名后把json返回给h5
                    [self postSignatureToJSWithStr:str];
                }
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [statusBar showStatusMessage:@"上传图片失败..."];
            });
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        });
        NSLog(@"上传图片后返回来的结果result = %@",result);
    } failure:^(NSError *error) {
    }];
}

- (void)viewDidDisappear:(BOOL)animated
{
    //清除UIWebView的缓存
    [self cleanCacheAndCookie];
}

- (void)dealloc
{
    //清除UIWebView的缓存
    [self cleanCacheAndCookie];
}

/**清除缓存和cookie*/
- (void)cleanCacheAndCookie
{
    //清除cookies
    NSLog(@"---------清除cookies");
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies])
    {
        [storage deleteCookie:cookie];
    }
    //清除UIWebView的缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
}
//
//- (void)returnSectionListsToFirtPageBlock:(returnSectionListsToFirtPageBlock)block
//{
//    self.sBlock = block;
//}
//
//- (void)returnProductsToFirtPageBlock:(returnProductsToFirtPageBlock)block
//{
//    self.pBlock = block;
//}
//
//- (void)returnImagesURLStringsToFirtPageBlock:(returnImagesURLStringsToFirtPageBlock)block
//
//{
//    self.iBlock = block;
//}


@end
